#!/bin/bash

# Flutter一键构建所有平台脚本
# 用法: ./build_all_platforms.sh [构建类型]
# 构建类型: debug, profile, release (默认: release)

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 获取构建类型参数
BUILD_TYPE=${1:-release}

# 获取应用信息
APP_NAME=$(grep "^name:" pubspec.yaml | cut -d' ' -f2)
VERSION=$(grep "^version:" pubspec.yaml | cut -d' ' -f2 | cut -d'+' -f1)

echo -e "${CYAN}🚀 Flutter一键构建所有平台${NC}"
echo -e "${YELLOW}应用名称:${NC} $APP_NAME"
echo -e "${YELLOW}版本号:${NC} $VERSION"
echo -e "${YELLOW}构建类型:${NC} $BUILD_TYPE"
echo -e "${YELLOW}开始时间:${NC} $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# 记录开始时间
START_TIME=$(date +%s)

# 要构建的平台列表
PLATFORMS=("android" "web")

# 如果是macOS系统，添加iOS和macOS构建
if [[ "$OSTYPE" == "darwin"* ]]; then
    PLATFORMS+=("ios" "macos")
fi

# 如果支持Linux构建，添加Linux
if command -v flutter >/dev/null 2>&1; then
    if flutter config | grep -q "enable-linux-desktop: true"; then
        PLATFORMS+=("linux")
    fi
fi

# 如果支持Windows构建，添加Windows  
if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "win32" ]]; then
    PLATFORMS+=("windows")
fi

# 成功和失败的构建记录
SUCCESSFUL_BUILDS=()
FAILED_BUILDS=()

echo -e "${BLUE}📋 将要构建的平台:${NC} ${PLATFORMS[*]}"
echo ""

# 遍历所有平台进行构建
for platform in "${PLATFORMS[@]}"; do
    echo -e "${PURPLE}🏗️  正在构建 $platform 平台...${NC}"
    
    # 执行构建
    if ./scripts/build_with_version.sh "$platform" "$BUILD_TYPE"; then
        SUCCESSFUL_BUILDS+=("$platform")
        echo -e "${GREEN}✅ $platform 构建成功${NC}"
    else
        FAILED_BUILDS+=("$platform")
        echo -e "${RED}❌ $platform 构建失败${NC}"
    fi
    
    echo ""
done

# 计算总用时
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
MINUTES=$((DURATION / 60))
SECONDS=$((DURATION % 60))

# 显示构建结果摘要
echo -e "${CYAN}📊 构建结果摘要${NC}"
echo -e "${YELLOW}总用时:${NC} ${MINUTES}分${SECONDS}秒"
echo -e "${YELLOW}完成时间:${NC} $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

if [ ${#SUCCESSFUL_BUILDS[@]} -gt 0 ]; then
    echo -e "${GREEN}✅ 构建成功的平台 (${#SUCCESSFUL_BUILDS[@]}个):${NC}"
    for platform in "${SUCCESSFUL_BUILDS[@]}"; do
        echo -e "  ${GREEN}• $platform${NC}"
    done
    echo ""
fi

if [ ${#FAILED_BUILDS[@]} -gt 0 ]; then
    echo -e "${RED}❌ 构建失败的平台 (${#FAILED_BUILDS[@]}个):${NC}"
    for platform in "${FAILED_BUILDS[@]}"; do
        echo -e "  ${RED}• $platform${NC}"
    done
    echo ""
fi

# 显示构建文件位置
if [ ${#SUCCESSFUL_BUILDS[@]} -gt 0 ]; then
    echo -e "${BLUE}📂 构建文件保存位置:${NC}"
    echo -e "  builds/ 目录"
    echo ""
    
    echo -e "${YELLOW}💡 提示:${NC}"
    echo -e "  • 可以使用 ${CYAN}ls -la builds/${NC} 查看所有构建文件"
    echo -e "  • 文件命名格式: ${APP_NAME}_v${VERSION}_{平台}_{构建类型}_{日期时间}.{扩展名}"
fi

# 根据结果设置退出码
if [ ${#FAILED_BUILDS[@]} -gt 0 ]; then
    echo -e "${YELLOW}⚠️  部分平台构建失败，请检查错误信息${NC}"
    exit 1
else
    echo -e "${GREEN}🎉 所有平台构建完成！${NC}"
    exit 0
fi